package com.entities.projectitem.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.core.hibernate.ExceptionHandler;
import com.core.hibernate.exceptionevent.ExceptionEvent;
import com.core.protocols.IKVObject;
import com.core.protocols.IServiceLayerDelegate;
import com.core.servlets.TaskTrackerServlet;
import com.core.utils.GlobalConstants;
import com.core.utils.ListUtils;
import com.core.utils.RequestParams;
import com.entities.projectitem.requestmapparser.ProjectItemMapParser;
import com.entities.projectitem.servicelayer.ProjectListLayer;
import com.entities.projecttask.servicelayer.ProjectTasksListLayer;
import com.model.project.ProjectItem;

/**
 * Servlet implementation class ProjectAdd
 */
public class ProjectAdd
        extends TaskTrackerServlet
        implements IServiceLayerDelegate {

	private HttpServletResponse postResponse     = null;

	private static final long   serialVersionUID = 1L;



	public ProjectAdd() {

	}



	@Override
	protected void doPost ( HttpServletRequest request,
	                        HttpServletResponse response )
	        throws ServletException, IOException {

		this.postResponse = response;

		RequestParams map = RequestParams.paramsFromRequest(request);
		ProjectItem template = ProjectItemMapParser.fromMap(map);

		ProjectListLayer projectListLayer = new ProjectListLayer();
		projectListLayer.setLayerDelegate(this);

		try {
			ProjectTasksListLayer.createEntityWithTemplate(template, this, null);
		} catch ( Exception e ) {
			ExceptionHandler.handleException(e, new ExceptionEvent(ExceptionEvent.POSTEVENT));
		}

		template = null;

	}



	@Override
	public <T> void responseResponseItemsList ( final List <T> items,
	                                            final Object request,
	                                            final Exception exception ) {

		T item = ListUtils.listItemAtIndex(items, 0);

		this.redirectItemIntoOpenServlet(item);

	}



	private <T> void redirectItemIntoOpenServlet ( T item ) {

		if ( this.postResponse == null ) {
			return;
		}

		String redirection = String.format("%s", GlobalConstants.SERVLET_PROJECTLIST);

		if ( item != null ) {
			if ( item instanceof IKVObject ) {
				IKVObject kvObject = (IKVObject) item;
				String idValue = kvObject.idValue().toString();
				redirection = String.format("%s?%s", GlobalConstants.SERVLET_PROJECTINFO, idValue);
			}
		}

		try {
			this.postResponse.sendRedirect(redirection);
		} catch ( IOException e ) {
			e.printStackTrace();
		}

	}

}
